import { Button } from "@/components/button";
import { Input } from "@/components/input";
import React, { useImperativeHandle, useRef } from "react";

interface RefType {
  focus: () => void;
}

/**
 * useImperativeHandle
 * 调用子组件的方法
 */

const FancyInput: React.FC<{
  ref: React.Ref<RefType>;
  defaultValue: number;
}> = ({ ref, defaultValue }) => {
  const inputRef = useRef<HTMLInputElement>(null);

  useImperativeHandle(
    ref,
    () => ({
      focus: () => {
        inputRef.current?.focus();
      },
    }),
    []
  );

  return <Input defaultValue={defaultValue} ref={inputRef} />;
};

export default function UseImperativeHandle() {
  const ref = useRef<RefType>(null);

  return (
    <>
      <div className="text-xl mb-4">React: useImperativeHandle</div>
      <Button
        onClick={() => {
          ref.current?.focus();
        }}
      >
        focus
      </Button>
      <FancyInput defaultValue={11} ref={ref} />
    </>
  );
}
